#include "CityCodeUtils.h"

#include <QFile>
#include <qjsonarray.h>
#include <qjsondocument.h>

CityCodeUtils::CityCodeUtils()
{

}

QString CityCodeUtils::getCItyCodeFromName(QString cityName)
{
    if(citymap.isEmpty())
    {
        //如果map里没有键值对 再去打开JSON表里去找对应的城市并放入map中
        initCityMap();
    }
    QMap<QString, QString>::iterator it = citymap.find(cityName);
    if(it == citymap.end())
    {
        it = citymap.find(cityName + "市");
        if(it == citymap.end())
        {
            it = citymap.find(cityName + "县");
        }
        if(it == citymap.end())
        {
            it = citymap.find(cityName + "区");
            if(it == citymap.end())
            {
                return "";
            }
        }
    }
    return it.value();
}

void CityCodeUtils::initCityMap()
{
    //打开Json文件
    QFile file(":/res/citycode.json");
    file.open(QIODevice::ReadOnly);
    QByteArray rawData = file.readAll();
    file.close();

    //解析Json文件
    QJsonDocument jsonDoc = QJsonDocument::fromJson(rawData);
    if(jsonDoc.isArray())
    {
        QJsonArray cities = jsonDoc.array();
        for(QJsonValue value : cities)
        {
            if(value.isObject())
            {
                QString cityName = value["city_name"].toString();
                QString cityCode = value["city_code"].toString();
                citymap.insert(cityName, cityCode);
            }
        }
    }
}
